﻿/*
    Copyright (C) 2008, wj2929, wj2929@gmail.com

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    *KEEP THIS HEADER INFORMATION*
*/

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Text.RegularExpressions;
using System.Web;
using System.Threading;
using mjRegister.Entity;
using mjRegister.BAL;

namespace mjRegister
{
    public partial class DelMJ : Form
    {
        int delayConnect = 3;//延迟间隔默认3秒

        private ListViewColumnSorter lvwColumnSorter;

        IList<SimpleUserInfo> allFriends = new List<SimpleUserInfo>();

        bool selectflag = false;

        IList<Thread> lstThread = new List<Thread>();

        User user = new User();

        public DelMJ()
        {
            InitializeComponent();
            lvwColumnSorter = new ListViewColumnSorter();
            this.listView1.ListViewItemSorter = lvwColumnSorter;
        }


        private void button1_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(this.txtUserName.Text.Trim()) || string.IsNullOrEmpty(this.txtPassword.Text.Trim()))
            {
                MessageBox.Show("账户或密码为空！");
                return;
            }

            if (user.Login(this.txtUserName.Text.Trim(), this.txtPassword.Text.Trim()))
            {
                this.button2.Enabled = true;
                this.button1.Enabled = false;
                this.button4.Enabled = true;

                //验证正确
                MessageBox.Show("成功登录！");
            }
            else
            {
                //错误
                MessageBox.Show("帐号或密码错误！");
            }
        }


        private void listView1_ColumnClick(object sender, ColumnClickEventArgs e)
        {
            // 检查点击的列是不是现在的排序列.
            if (e.Column == lvwColumnSorter.SortColumn)
            {
                // 重新设置此列的排序方法.
                if (lvwColumnSorter.Order == SortOrder.Ascending)
                {
                    lvwColumnSorter.Order = SortOrder.Descending;
                }
                else
                {
                    lvwColumnSorter.Order = SortOrder.Ascending;
                }
            }
            else
            {
                // 设置排序列，默认为正向排序
                lvwColumnSorter.SortColumn = e.Column;
                lvwColumnSorter.Order = SortOrder.Ascending;
            }

            // 用新的排序方法对ListView排序
            this.listView1.Sort();

        }




        private void button4_Click(object sender, EventArgs e)
        {
            //所有好友
            allFriends = user.GetAllUserInfos();

            FillListView(allFriends);

            //所有群组
            this.ddlgroup.Items.Clear();
            IList<GroupInfo> groupInfos = user.GetGroupInfos();
            groupInfos.Insert(0, new GroupInfo { Name = "全部好友" });
            for (int i = 0; i < groupInfos.Count; i++)
            {
                this.ddlgroup.Items.Add(groupInfos[i].Name);
            }

            this.ddlgroup.SelectedIndex = 0;

            ddlgroup.Enabled = true;
            this.button5.Enabled = true;
            this.textBox1.Enabled = true;
            this.button6.Enabled = true;
            this.button3.Enabled = true;
        }

        private void button5_Click(object sender, EventArgs e)
        {
            this.listView1.Items.Clear();
            IList<ListViewItem> listViewItems = new List<ListViewItem>();
            for (int i = 0; i < allFriends.Count; i++)
            {
                SimpleUserInfo userInfo = allFriends[i];
                if (userInfo.real_name.Contains(this.textBox1.Text))
                {
                    ListViewItem item = new ListViewItem(new string[] { userInfo.uid, userInfo.real_name });
                    item.Tag = userInfo;
                    listViewItems.Add(item);
                }
            }
            this.listView1.Items.AddRange(GetArray<ListViewItem>.Get(listViewItems));
        }

        void FillListView(IList<SimpleUserInfo> userInfos)
        {
            this.listView1.Items.Clear();
            for (int i = 0; i < userInfos.Count; i++)
            {
                SimpleUserInfo userInfo = userInfos[i];
                ListViewItem item = new ListViewItem(new string[] { userInfo.uid, userInfo.real_name });
                item.Tag = userInfo;
                this.listView1.Items.Add(item);
            }
        }

        private void button6_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < this.listView1.Items.Count; i++)
            {
                this.listView1.Items[i].Checked = !selectflag;
            }
            selectflag = !selectflag;
        }

        void DeleteFriend(object obj)
        {
            IList<SimpleUserInfo> userInfos = (List<SimpleUserInfo>)obj;
            for (int i = 0; i < userInfos.Count; i++)
            {
                SimpleUserInfo userInfo = (SimpleUserInfo)userInfos[i];
                user.DeleteFriend(userInfo);
                this.Invoke(new DSetProgressBarValue(SetProgressBarValue), string.Format("删除好友进度：({0},{1})，{2}", userInfo.uid, userInfo.real_name, string.Format("{0}/{1}", (i + 1).ToString(), userInfos.Count.ToString())), i);
                if(i + 1 < userInfos.Count)
                    Thread.Sleep(delayConnect * 1000);
            }
            this.Invoke(new DSetProgressBarValue(SetProgressBarValue), "删除好友完成！", userInfos.Count);
            this.Invoke(new DReLoadUserInfos(ReLoadUserInfos));
            MessageBox.Show("删除好友完成！");
        }

        delegate void DReLoadUserInfos();
        void ReLoadUserInfos()
        {
            this.button4_Click(this.button4, EventArgs.Empty);
        }

        delegate SimpleUserInfo DGetUserInfoFromListViewItemTag(ListViewItem listViewItem);
        SimpleUserInfo GetUserInfoFromListViewItemTag(ListViewItem listViewItem)
        {
            return (SimpleUserInfo)listViewItem.Tag;
        }

        private void button3_Click(object sender, EventArgs e)
        {
            IList<SimpleUserInfo> userInfos = new List<SimpleUserInfo>();

            for (int i = 0; i < this.listView1.Items.Count; i++)
            {
                if (this.listView1.Items[i].Checked)
                {
                    SimpleUserInfo userInfo = (SimpleUserInfo)this.listView1.Items[i].Tag;
                    userInfos.Add(userInfo);
                }
            }
            if (userInfos.Count == 0)
            {
                MessageBox.Show("尚未选择项！");
                return;
            }
            if (MessageBox.Show(string.Format("确定删除选择的{0}位好友？", userInfos.Count.ToString()), "请确定", MessageBoxButtons.OKCancel) == DialogResult.OK)
            {
                this.label6.Visible = true;
                this.progressBar1.Visible = true;
                this.progressBar1.Maximum = userInfos.Count;
                Thread t = new Thread(new ParameterizedThreadStart(DeleteFriend));
                t.Start(userInfos);
                lstThread.Add(t);
            }
        }

        delegate void DSetProgressBarValue(string labeltext,int value);
        void SetProgressBarValue(string labeltext,int value)
        {
            this.label6.Text = labeltext;
            this.progressBar1.Value = value;
        }

        private void button7_Click(object sender, EventArgs e)
        {
            try
            {
                delayConnect = int.Parse(this.textBox2.Text.Trim());
            }
            catch (Exception ex)
            {
                MessageBox.Show("【执行间隔】应填写整型数字！");
                return;
            }
            if (delayConnect <= 0)
            {
                MessageBox.Show("【执行间隔】应大于0，将恢复默认值：5！");
                delayConnect = 5;
                this.textBox2.Text = delayConnect.ToString();
                return;
            }
            MessageBox.Show(string.Format("设置成功，当前执行间隔修改为{0}秒", delayConnect.ToString()));
        }

        private void button2_Click(object sender, EventArgs e)
        {
            Stop();
            user.Logout();
            this.listView1.Items.Clear();
            this.button2.Enabled = false;
            this.button1.Enabled = true;
            this.label6.Visible = false;
            this.progressBar1.Visible = false;
            ddlgroup.Enabled = false;
            this.button5.Enabled = false;
            this.textBox1.Enabled = false;
            this.button6.Enabled = false;
            this.button3.Enabled = false;
            this.button4.Enabled = false;
            MessageBox.Show("退出ok！");
        }

        private void ddlgroup_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.ddlgroup.SelectedIndex != 0)
            {
                FillListView(user.GetUserInfosByGroup(this.ddlgroup.Text));
            }
            else
            {
                FillListView(allFriends);
            }
        }

        public void Stop()
        {
            for (int i = 0; i < lstThread.Count; i++)
            {
                if (lstThread[i].IsAlive)
                    lstThread[i].Abort();
            }
        }

        private void button8_Click(object sender, EventArgs e)
        {
            Stop();
            this.Close();
        }

        private void DelMJ_FormClosing(object sender, FormClosingEventArgs e)
        {
            Stop();
        }
    }
}
